import { getCollection } from '@/service/collection';
import { AddAppParams, IApp, UpdateAppParams } from '@/service/types';
import { pick } from 'lodash-es';

export const roleCollection = getCollection<IApp>('opendb-app-list');

const fields = ['appid', 'name', 'introduction', 'introduction'];

const existApp = async (appid: string) => {
	try {
		const res = await roleCollection.where({ appid }).getOne();
		return !!res.data;
	} catch (error) {
		throw error;
	}
};

const existAppById = async (id: string) => {
	try {
		const res = await roleCollection.where({ _id: id }).getOne();
		return !!res.data;
	} catch (error) {
		throw error;
	}
};
const getAllApp = async () => {
	try {
		const res = await roleCollection.get();
		return res.data;
	} catch (error) {
		throw error;
	}
};

const getPaginationApp = async (params: PaginationParams) => {
	try {
		const res = await roleCollection
			.where(params.query ? params.query : {})
			.limit(params.limit)
			.skip(params.skip)
			.get({ getCount: true });
		return res;
	} catch (error) {
		throw error;
	}
};
const addApp = async (data: AddAppParams) => {
	try {
		const exist = await existApp(data.appid);
		if (exist) {
			throw new Error('标签已存在');
		}

		const pickData = pick(data, fields);

		const res = await roleCollection.add(pickData);
		return res.id;
	} catch (error) {
		throw error;
	}
};

const updateApp = async (data: UpdateAppParams) => {
	const exist = await existAppById(data._id);
	if (!exist) {
		throw new Error('标签不存在');
	}
	const pickData = pick(data, fields);
	try {
		const res = await roleCollection
			.where({
				_id: data._id,
			})
			.update(pickData);
		return res.updated;
	} catch (error) {
		throw error;
	}
};

const deleteApp = async (id: string) => {
	try {
		const res = await roleCollection.where({ _id: id }).remove();
		return res.deleted;
	} catch (error) {
		throw error;
	}
};
export const app = {
	getAllApp,
	addApp,
	updateApp,
	getPaginationApp,
	deleteApp,
};
